package com.se.xb.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;


public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取请求URI的最后一部分，去掉查询参数
        String requestURI = request.getRequestURI();
        int queryIndex = requestURI.indexOf('?');
        if (queryIndex != -1) {
            requestURI = requestURI.substring(0, queryIndex);
        }
        String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);

        // 调用目标方法
        boolean methodFound = false;
        for (Method method : this.getClass().getMethods()) {
            if (method.getName().equals(methodName) && method.getParameterTypes().length == 2) {
                try {
                    // 调用目标方法
                    method.invoke(this, request, response);
                    methodFound = true;
                    break;
                } catch (Exception e) {
                    response.getWriter().write("方法调用失败: " + e.getMessage());
                    return;
                }
            }
        }
        if (!methodFound) {
            response.getWriter().write("方法或页面不存在");
        }
    }
}